
import Vue from 'vue'
import { accessToken } from '@/env'
import { getUserPermissions, getUserInfo } from '@/api'
import { userTypeEnum } from '@/core/enum'
import OrderTimer from '@/core/order'
import { USER_AUTHENTICATE, USER_ACCOUNT, USER_LOGOUT, USER_PROFILE, USER_IS_SUPER, USER_START_TIMER } from '../mutation-types'

const state = {
  isAuthenticated: false,
  permissions: [],
  account: {},
  isSuper: false,
  isStartOrderTimer: false
}

const mutations = {
  [USER_AUTHENTICATE] (state, bool) {
    state.isAuthenticated = bool
  },
  [USER_IS_SUPER] (state, bool) {
    state.isSuper = bool
  },
  [USER_START_TIMER] (state, bool) {
    state.isStartOrderTimer = bool
  },
  [USER_PROFILE] (state, data) {
    const { allFunctionPermissionCodeList } = data
    state.permissions = allFunctionPermissionCodeList || []
  },
  [USER_LOGOUT] (state) {
    state.account = {}
    state.permissions = []
    state.isAuthenticated = false
    state.isSuper = false
    state.isStartOrderTimer = false
    Vue.ls.remove(accessToken)
    // 切换账号未刷新页面时手动关闭定时器
    OrderTimer.stop()
  },
  [USER_ACCOUNT] (state, data) {
    let newState = Object.assign({}, state.account, data)
    state.account = newState
  }
}

const actions = {
  doGetAuthInfo ({ commit }) {
    return new Promise((resolve, reject) => {
      getUserPermissions().then(res => {
        // if (res.result === httpStatus.OK) {
        // eslint-disable-next-line no-constant-condition
        if (true) {
          commit(USER_AUTHENTICATE, true)
          commit(USER_PROFILE, res.data)
          resolve()
        } else {
          reject(res.message)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  doGetUserInfo ({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        commit(USER_ACCOUNT, res.data)
        commit(USER_IS_SUPER, +res.data.userType === userTypeEnum.super)
        commit(USER_START_TIMER, +res.data.userType === userTypeEnum.startTimer)

        if (+res.data.userType === userTypeEnum.startTimer) {
          OrderTimer.start()
        }

        resolve()
      })
    })
  },

  doLogout ({ commit }) {
    commit(USER_LOGOUT)
    return Promise.resolve()
  },

  updateAccount ({ commit }, partial) {
    commit(USER_ACCOUNT, partial)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
